﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using NHibernate;
using YunBox2.Contracts;
using YunBox2.Contracts.Core;

namespace YunBox2.Server.Core
{
	public class UserOperation
	{
		private readonly SessionContext _sessionContext;
		private readonly ISession _session;

		public UserOperation(ISession session, SessionContext sessionContext)
		{
			if (sessionContext == null)
			{
				throw new ArgumentNullException("sessionContext");
			}
			_session = session;
			_sessionContext = sessionContext;
		}

		public IList<User> GetUserList()
		{
			IList<User> userList = _session.QueryOver<User>().Where(x => x.IsDisable == false).List<User>();
			return userList;
		}

		public IList<User> GetAllUsers()
		{
			IList<User> userList = _session.QueryOver<User>().List<User>();
			return userList;
		}

		public User GetUserByName(string name)
		{
			var user = _session.QueryOver<User>().Where(x => x.UserName == name).SingleOrDefault<User>();
			return user;
		}

		public bool Logon(string name, string password)
		{
			User user = GetUserByName(name);
			if (user == null || user.IsDisable)
			{
				throw new FaultException<string>("用户不存在或已过期");
			}

			if (user.Password == password)
			{
				user.LastLoginTime = DateTime.Now;
				_session.Update(user);
				_sessionContext.CurrentUser = user;
				return true;
			}

			return false;
		}

		public bool Logoff()
		{
			User user = _sessionContext.CurrentUser;
			user.LastLogoutTime = DateTime.Now;

			_session.SaveOrUpdate(user);
			_sessionContext.CurrentUser = null;
			return true;
		}

		public bool ChangePassword(string oldPassword, string newPassword)
		{
			User user = _sessionContext.CurrentUser;
			if (user == null)
			{
				throw new FaultException<string>("用户未登录");
			}

			if (user.Password == oldPassword)
			{
				throw new FaultException<string>("用户密码错误");
			}
			user.Password = newPassword;
			user.LastChangedPassword = DateTime.Now;
			//try
			//{
			_session.Update(user);
			_session.Flush();
			return true;
			//}
			//catch
			//{
			//	throw new FaultException<string>("密码修改失败.数据库连接失败");
			//}
		}

		public User CreateUser(User newUser)
		{
			if(newUser.Id.HasValue && newUser.Id.Value!=Guid.Empty)
			{
				var user = _session.Load<User>(newUser.Id.Value);
				if(user!=null)
				{
					newUser.Id = null;
				}
			}
			_session.Save(newUser);
			return newUser;
		}

		public User UpadteUser(User user)
		{
			user.LastModifiedTime = DateTime.Now;
			user.LastModifiedUser = _sessionContext.CurrentUser;
			_session.Merge(user);
			_session.Flush();
			return user;
		}

		public bool DisableUser(Guid userID)
		{
			var user = _session.Load<User>(userID);
			if (user != null)
			{
				user.IsDisable = true;
				//try
				//{
				_session.Update(user);
				_session.Flush();
				return true;
				//}
				//catch
				//{
				//	return false;
				//}
			}
			return false;
		}
	}
}